#include "core.h"
#include <memory>

#include "libgo.h"
#include "libzqutil/util.h"

namespace libzq
{
	co_chan<char> _close_chan;
	void sigroutine(int dunno)
	{
		_close_chan << 1;
	}

	Core::Core()
	{
		run();
	}
	Core & Core::instance()
	{
		static Core instance_;
		return instance_;
	}
	boost::asio::io_service & Core::ioservice()
	{
		return _io_service;
	}

	void Core::stop()
	{
		for (auto cb : _stop_vec)
		{
			try
			{
				cb();
			}
			catch (...)
			{

			}
		}
		_io_service.stop();
	}

	void Core::install_signals()
	{
		signal(SIGKILL, sigroutine); //* 下面设置三个信号的处理方法
		signal(SIGINT, sigroutine);
		go[this]()
		{
			char c;
			_close_chan >> c;
			stop();
		};
	}

	void Core::install_stop(func_stop_t cb)
	{
		_stop_vec.push_back(cb);
	}

	void Core::run_until_stop(const std::string&& task_name, func_run_t task, func_stop_t cb, unsigned int interval)
	{
		_task_map[task_name] = false;
		CORE.install_stop([this, task_name, task]()
		{
			_task_map[task_name] = true;
		});
		go[this, task_name, task, cb, interval]()
		{
			while (!_task_map[task_name])
			{
				task();
				if (interval) co_sleep(interval * 1000);
			}
			LOGT("Task [ %s ] end", task_name);
			cb();
		};
	}

	void Core::run()
	{
		go[this]()
		{
			_io_service.run();
		};
	}
}